package main

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

type UserInfo struct {
	UserName string
	Password string
	Hobbies  []string
}

func main() {
	r := gin.Default()

	// GET http://localhost/path?id=1234&name=Manu&value=&hobbies=football&hobbies=basketball
	r.GET("/path", func(c *gin.Context) {
		id := c.Query("id")
		name := c.Query("name")
		value := c.Query("value")                   // ""
		hobbies := c.QueryArray("hobbies")          // 数组
		unknow := c.DefaultQuery("unknow", "afans") // use the default string afans

		fmt.Printf("GET Query ==>  id:%s, name:%s, value:%s, hobbies:%#v, unknow:%s\n", id, name, value, hobbies, unknow)

		c.String(http.StatusOK, "welcome my friend, %s!!!", name)
	})

	// POST /user?username=liuxd&password=123
	// body {
	// 			"username": {"afans"},
	// 			"password": {"123456"},
	// 			"hobbies":  {"football", "basketball"},
	// }
	// http 常见的表单传输格式有四种：
	// 		application/json					===>
	// 		application/x-www-form-urlencoded	===> POST的默认方式
	// 		application/xml						===>
	// 		multipart/form-data					===> 传大文件使用？？？
	// PostForm 默认为x-www-form-urlencoded和form-data格式
	r.POST("/user", func(c *gin.Context) {
		// url参数
		userName := c.Query("username")
		// password := c.Query("Password")		// url默认区分大小写，如何设置不区分大小写？？？？？？？？？？
		password := c.Query("password")

		// body参数
		var u UserInfo
		u.UserName = c.PostForm("username")
		u.Password = c.PostForm("password")
		// u.Hobbies = c.PostFormArray("Hobbies")	// body默认区分大小写，如何设置不区分大小写？？？？？？？？？？
		u.Hobbies = c.PostFormArray("hobbies")

		var data = map[string]string{
			"url":  fmt.Sprintf("name:%s, password:%s", userName, password),
			"body": fmt.Sprintf("user:%#v", u),
		}

		fmt.Printf("Post data:%#v\n", data)

		c.JSON(http.StatusOK, gin.H{
			"code": "200",
			"msg":  data,
		})
	})

	// 获取API参数 http://localhost/param/afans/dance
	r.GET("/param/:name/*action", func(c *gin.Context) {
		name := c.Param("name")
		action := c.Param("action")

		// 截去/
		action = strings.Trim(action, "/")

		fmt.Printf("Param name:%s, action:%s\n", name, action)
		c.String(http.StatusOK, fmt.Sprintf("Param name:%s, action:%s\n", name, action))
	})

	r.Run(":80")
}
